<template>
  <a-card>
    <div v-show="showSpin">
      <a-spin tip="正在导出..." size="large">
        <div class="spin-content"></div>
      </a-spin>
    </div>
    <a-form-model :model="searchForm" v-bind="layout">
      <a-row>
        <!-- 搜索栏 -->
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            ref="inventoryOrganizationFileId"
            label="仓库名称"
            prop="inventoryOrganizationFileId"
          >
            <a-select
              v-model="searchForm.inventoryOrganizationFileId_dictText"
              showSearch
              @change="DepotNameChange"
            >
              <a-select-option
                v-for="item in WarehouseCodeList"
                :key="item.id"
                :value="
                  item.depotNo + '|' + item.depotName + '|' + item.pkStordoc
                "
                >{{ item.depotNo }} {{ item.depotName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item ref="sort" label="存货分类" prop="sort">
            <a-tree-select
              showSearch
              v-model="searchForm.sort"
              style="width: 100%"
              allow-clear
              :tree-data="inventoryNoList"
              @change="sortchangeSearch"
              onSelect
              tree-node-filter-prop="title"
              :replace-fields="replaceFields"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            ref="inventoryName"
            label="存货名称"
            prop="inventoryName"
          >
            <!-- <a-input disabled v-model="searchForm.inventoryName"></a-input> -->
            <a-select
              v-model="searchForm.inventoryName"
              @search="handleSearch"
              @change="inventoryNameChange"
              showSearch
            >
              <a-select-option
                v-for="val in inventoryList"
                :key="val.id"
                :value="
                  val.invcode +
                  '|' +
                  val.inventoryName +
                  '|' +
                  val.invspec +
                  '|' +
                  val.unit +
                  '|' +
                  val.inventoryInformationId
                "
                >{{ val.invcode }} {{ val.inventoryName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="存货编码">
            <a-input disabled v-model="searchForm.invcode"></a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col align="right">
          <a-button type="primary" @click="getSearch"> 查询</a-button>
          <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
            重置
          </a-button>
        </a-col>
      </a-row>

      <a-row>
        <a-button
          :style="{ marginRight: '8px' }"
          type="primary"
          @click="Template"
        >
          Excel模板下载
        </a-button>
        <a-button :style="{ marginRight: '8px' }" @click="exportToExcel">
          导出
        </a-button>

        <a-button
          type="primary"
          @click="addModal"
          style="margin-bottom: 10px"
          :style="{ marginRight: '8px' }"
        >
          <a-icon type="plus" />
          添加期初数据
        </a-button>
        <a-upload
          class="upload-demo"
          ref="upload"
          action=""
          :auto-upload="false"
          :file-list="fileList"
          :customRequest="CustomRequest"
          @change="HandleChange"
          :show-file-list="false"
        >
          <a-button>
            <a-icon type="upload" />
            导入
          </a-button>
        </a-upload>
      </a-row>
      <!-- 添加期初数据彈窗开始 -->
      <a-modal
        ref="collectionForm"
        :visible="addVisible"
        width="70%"
        title="添加期初数据"
        okText="提交"
        @cancel="addCancel"
        @ok="addOk"
      >
        <a-form-model ref="ruleForm" :model="addForm" v-bind="layout">
          <a-row>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item label="仓库名称">
                <a-select
                  v-model="addForm.depotName"
                  showSearch
                  @change="addWarehouse"
                >
                  <a-select-option
                    v-for="item in WarehouseCodeList"
                    :key="item.depotNo"
                    :value="item.depotNo + '|' + item.depotName + '|' + item.id"
                    >{{ item.depotNo }} {{ item.depotName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item ref="sort" label="存货分类" prop="sort">
                <a-tree-select
                  showSearch
                  v-model="addForm.sort"
                  style="width: 100%"
                  allow-clear
                  placeholder=""
                  :tree-data="inventoryNoList"
                  @change="sortchange"
                  onSelect
                  tree-node-filter-prop="title"
                  :replace-fields="replaceFields"
                >
                </a-tree-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item label="存货编码">
                <a-input disabled v-model="addForm.invcode"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item label="存货名称">
                <!-- <a-input disabled v-model="addForm.inventoryName"></a-input> -->
                <a-select
                  v-model="addForm.inventoryName"
                  @search="handleSearch"
                  @change="addinventoryNameChange"
                  showSearch
                >
                  <a-select-option
                    v-for="val in inventoryList"
                    :key="val.id"
                    :value="
                      val.invcode +
                      '|' +
                      val.inventoryName +
                      '|' +
                      val.invspec +
                      '|' +
                      val.unit +
                      '|' +
                      val.inventoryInformationId
                    "
                    >{{ val.invcode }} {{ val.inventoryName }}{{ val.invspec }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item label="规格型号">
                <a-input disabled v-model="addForm.invspec"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item ref="unit" label="单位" prop="unit">
                <a-input disabled v-model="addForm.unit"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item ref="balance" label="结存数量" prop="balance">
                <a-input placeholder="" v-model="addForm.balance" />
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item
                ref="balanceAmount"
                label="结存金额"
                prop="balanceAmount"
              >
                <a-input placeholder="" v-model="addForm.balanceAmount" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item
                ref="createtime"
                label="创建时间"
                prop="createtime"
              >
                <a-date-picker
                  v-model="addForm.createTime"
                  type="date"
                  placeholder="年/月/日 "
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  :defaultValue="moment()"
                />
              </a-form-model-item>
            </a-col>

            <a-col :xl="8" :lg="8" md="8" :sm="24">
              <a-form-model-item
                ref="starttime"
                label="账龄起始日期"
                prop="starttime"
              >
                <a-date-picker
                  v-model="addForm.startTime"
                  type="date"
                  placeholder="年/月/日 "
                  style="width: 100%"
                  format="YYYY-MM-DD"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-modal>
      <!-- 新增期初数据结束 -->
    </a-form-model>

    <!-- 表格 -->

    <a-table
      bordered
      :data-source="dataSource"
      :columns="columns"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ x: 1800 }"
      id="myTable"
    >
      <!-- <template slot="序号" slot-scope="text, record">
        <editable-cell
          :text="text"
          @change="onCellChange(record.key, 'num', $event)"
        />
      </template> -->
      <template slot="caozuo" slot-scope="text, record">
        <!-- 修改按钮与修改页面 -->
        <span slot="action">
          <a type="primary" @click="editRecord(record)"> 修改 </a>&nbsp;
        </span>
        <!-- 删除提示 -->
        <a-popconfirm
          v-if="dataSource.length"
          title="确定删除吗?"
          @confirm="() => onDelete(record.id)"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm>
      </template>
    </a-table>
    <!-- 修改弹窗开始 -->
    <a-modal
      title="修改期初数据"
      :visible="visible1"
      width="70%"
      :labelCol="{ span: 8 }"
      :WapperCol="{ span: 5 }"
      @ok="updateData"
      @cancel="handleCancel1"
      cancelText="取消"
      okText="保存"
    >
      <a-form-model ref="ruleForm" :model="updateForm" v-bind="layout">
        <a-row>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item
              ref="depotName"
              label="仓库名称"
              prop="depotName"
            >
              <a-input
                v-model="updateForm.inventoryOrganizationFileId_dictText"
                disabled
              >
              </a-input>
            </a-form-model-item>
          </a-col>

          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="存货分类">
              <a-input v-model="updateForm.sort_dictText" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="存货编码">
              <a-input v-model="updateForm.invcode" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item
              ref="inventoryName"
              label="存货名称"
              prop="inventoryName"
            >
              <a-input disabled v-model="updateForm.inventoryName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="规格型号">
              <a-input disabled v-model="updateForm.invspec"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="单位">
              <a-input disabled v-model="updateForm.unit"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="结存数量">
              <a-input placeholder="" v-model="updateForm.balance" />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="结存金额">
              <a-input placeholder="" v-model="updateForm.balanceAmount" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="创建时间">
              <a-date-picker
                v-model="updateForm.createTime"
                type="date"
                placeholder="年/月/日 "
                style="width: 100%"
                format="YYYY - MM - DD"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" md="8" :sm="24">
            <a-form-model-item label="账龄起始日期">
              <a-date-picker
                v-model="updateForm.startTime"
                type="date"
                placeholder="年/月/日 "
                style="width: 100%"
                format="YYYY-MM-DD"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <!-- 修改弹窗结束 -->
  </a-card>
</template>

<script>
import moment from "moment";
import "moment/locale/zh-cn";
import FileSaver from "file-saver";
import XLSX from "xlsx";
// import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao";
import {
  CommonAjax,
  //uploadExcel,
  //getStaticFileURL,
} from "@/services/modules/common";
import { QiChuShuJuLuRuHttp } from "@/services/modules/QiChuShuJu/QiChuShuJuLuRu";
// import { deepClone } from "@/utils/index.js";
import { sheet2blob } from "@/utils/export.js";
import axios from "axios";
// import axios from "_axios@0.19.2@axios";
import { AJAX_PATH } from "@/services/config";

const $http = new QiChuShuJuLuRuHttp();
// const $ZDB = new ZiDianBiaoHttp();
const comHttp = new CommonAjax(); // 公用接口
const columns = [
  {
    title: "序号",
    key: 1,
    dataIndex: "num",
    width: "5%",
    align: "center",
    scopedSlots: { customRender: "num" },
  },
  {
    title: "仓库名称",
    key: 2,
    dataIndex: "inventoryOrganizationFileId_dictText",
    width: "10%",
    align: "center",
  },
  {
    title: "存货分类",
    key: 4,
    dataIndex: "sort_dictText",
    align: "center",
  },
  {
    title: "存货编码",
    key: 5,
    dataIndex: "invcode",
    align: "center",
  },
  {
    title: "存货名称",
    key: 6,
    dataIndex: "inventoryInformationId_dictText",
    align: "center",
  },
  {
    title: "规格型号",
    key: 7,
    dataIndex: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: 8,
    dataIndex: "unit",
    align: "center",
  },
  {
    title: "结存数量",
    key: 9,
    dataIndex: "balance",
    align: "center",
  },
  {
    title: "结存金额",
    key: 10,
    dataIndex: "balanceAmount",
    align: "center",
  },
  {
    title: "创建时间",
    key: 11,
    dataIndex: "createTime",
    align: "center",
  },
  {
    title: "账龄起始日期",
    key: 12,
    dataIndex: "startTime",
    align: "center",
  },
  {
    title: "账龄(天)",
    key: 13,
    dataIndex: "age",
    align: "center",
  },
  {
    title: "操作",
    key: 14,
    width: 100,
    dataIndex: "caozuo",
    fixed: "right",
    scopedSlots: { customRender: "caozuo" },
    align: "center",
  },
];

const dataSource = []; //表格数据
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
};

export default {
  data() {
    return {
      fileList: [],
      file: "",
      replaceFields: {
        children: "syncInventoryClassificationEntityList",
        title: "invclassname",
        value: "pkInvcl",
      },
      moment, //当前时间
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
        hosName: "",
        hosCode: "",
        province: "",
        city: "",
      },
      //===============分页========================
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },
      // startTime: "", //账龄起始日期
      age: "", //账龄

      inventoryList: [], //存货编码、名称、规格型号、单位
      inventoryNoList: [], //存货分类列表
      WarehouseCodeList: [], //所有的仓库编码、仓库名称、id

      //新增弹窗
      addVisible: false,
      addForm: {
        depotName: "", //仓库名称
        storageUnit: "", //所属单位
        sort: "", //存货分类
        inventoryInformationId: "", //存货ID
        invcode: "", //存货编码
        inventoryName: "", //存货名称
        invspec: "", //规格型号
        unit: "", //单位
        balance: "", //结存数量
        balanceAmount: "", //结存金额
        createtime: "", //创建时间
        starttime: "", //账龄起始日期
        // accoutAge: "", //账龄
      },
      showSpin: false, //打印加载中
      visible1: false, //修改弹窗
      // --- 修改表单 ---
      updateForm: {
        balanceAmount: 0, // 结存金额
        balance: 0, //结存数量
        createTime: "", //创建时间
        id: 0, //id

        // inventoryInformationId: 0, //存货id
        // inventoryInformationId_dictText: "", //存货名称
        // inventoryName: "", //存货名称
        // inventoryNo: "", //存货编码
        inventoryOrganizationFileId: 0, //仓库名称id
        inventoryOrganizationFileId_dictText: "", // 仓库名称
        key: 0, //key
        num: 0, //序号
        sort: 0, //存货分类
        sort_dictText: "", //分类
        invspec: "", //规格型号
        startTime: "", //账龄起始日期
        unit: "", // 单位
      },

      searchForm: {
        //查询的表单
        inventoryOrganizationFileId: "", //仓库名称
        sort: "", //存货分类
        invcode: "", //存货编码
        inventoryName: "", //存货名称
      },

      // 增加栏的格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      // 表格数据

      count: 2,
      dataSource, //表格数据
      dataSourceCache: [], // 缓存数据
      columns, //表格
      rowSelection, //按行勾选

      queryPathCache: "", // 查询缓存
    };
  },

  mounted() {
    this.getInventoryClassificationList(); // 获取存货分类
    // this.getInventoryInformationByStorageId(); // 存货信息档案-返回存货编码、名称、规格型号、单位
    this.getApplyStorage(); // 获取仓库编码、名称
    this.GetBeginningDataentryList(); // 获取期初数据列表 渲染 table
  },
  methods: {
    Template() {
      comHttp.downloadTemplete().then((res) => {
        console.log("期初数据模板下载", res);
         //如果后端返回的result是进过Blob处理的，直接 window.URL.createObjectURL(result)，如果没有，就需要先实例化new Blod处理之后再window.URL.createObjectURL(blob)。
        //文件名 文件保存对话框中的默认显示
        let fileName = "期初数据模板.xls";
        let data = res.data;
        if (!data) {
          return;
        }
        console.log(res);
        //构造a标签 通过a标签来下载
        let url = window.URL.createObjectURL(new Blob([data]));
        let a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        //此处的download是a标签的内容，固定写法，不是后台api接口
        a.setAttribute("download", fileName);
        document.body.appendChild(a);
        //点击下载
        a.click();
        // 下载完成移除元素
        document.body.removeChild(a);
        // 释放掉blob对象
        window.URL.revokeObjectURL(url);
      });
    },

    CustomRequest(options) {
      const curFile = options.file; //拿到上传文件
      console.log("----curFile-----", curFile);
      if (!curFile) return; //判断文件是否为空
      // 生成 FormData 上传数据
      // 并设置 files 字段 填充数据
      let formData = new FormData();
      formData.append("file", curFile);

      axios({
        method: "post",
        url: AJAX_PATH.uploadExcel,
        headers: {
          "Content-Type": "multipart/form-data",
          "X-Access-Token": JSON.parse(
            localStorage.getItem("zhqh-pro-token")
          ),
        },
        data: formData,
        responseType: "arraybuffer",
      })
        .then((response) => {
          //文件名 文件保存对话框中的默认显示
          let fileName = "导入结果.xlsx";
          let data = response.data;
          if (!data) {
            return;
          }
          console.log(response);
          //构造a标签 通过a标签来下载
          let url = window.URL.createObjectURL(new Blob([data]));
          let a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          //此处的download是a标签的内容，固定写法，不是后台api接口
          a.setAttribute("download", fileName);
          document.body.appendChild(a);
          //点击下载
          a.click();
          // 下载完成移除元素
          document.body.removeChild(a);
          // 释放掉blob对象
          window.URL.revokeObjectURL(url);
        })
        .catch((response) => {
          this.$message.error(response);
        });
      /*uploadExcel(formData, (response) => {
        this.uid--;
        if (response.success) {
          this.$message.success("导入成功！");
          this.GetBeginningDataentryList();
        } else {
          this.$message.error("导入失败！");
        }
      });*/
      console.log(this.response, "this.response");

      console.log("this.attachmentFileList:::", this.attachmentFileList);
    },
    HandleChange({ file, fileList }) {
      console.log("file::", file);
      // 此处判断上传的文件的状态，如果是uploading则跳出
      if (file.status == "uploading") return;
      // 此处判断上传的文件的状态，如果是removed将其移除
      if (file.status == "removed") {
        this.fileList.shift(file);
      }
      console.log(fileList);
      this.fileList = fileList;
      console.log("HandleChange::", this.fileList);
    },
    handleSearch(value) {
      //模糊查询
      this.inventoryList = [];
      console.log("value", value);
      let query = "?name=" + value;
      console.log("query", query);
      if (value == "" || value == null) {
        this.NumberAndList = [];
      } else {
        comHttp.getgetSearchInventoryInformationFile(query).then((res) => {
          console.log("结果为======================", res);
          // this.goodsList = res.result;
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              inventoryInformationId: res.result[i].pkInvbasdoc, // 存货 id
              invcode: res.result[i].invcode, //存货编码
              inventoryName: res.result[i].invname, //存货名称
              invspec: res.result[i].invspec, //规格型号
              unit: res.result[i].measname, //单位
            };
            this.inventoryList.push(data);
          }
        });
      }
    },
    // --- 查询搜索 ---
    getSearch() {
      console.log(this.addForm, 11);
      const searchForm = this.searchForm;
      let queryPath = "";
      if (searchForm.inventoryOrganizationFileId) {
        queryPath += `&inventoryOrganizationFileId=${searchForm.inventoryOrganizationFileId}`;
      }
      if (searchForm.sort) {
        queryPath += `&sort=${searchForm.sort}`;
      }
      if (searchForm.inventoryInformationId) {
        queryPath += `&inventoryInformationId=${searchForm.inventoryInformationId}`;
      }

      this.queryPathCache = queryPath;

      this.GetBeginningDataentryList(); //获取列表
    },

    // 获取期初数据录入列表
    // GetBeginningDataentryList(queryPath = "?pageNo=" + this.queryParam.page) {
    GetBeginningDataentryList() {
      this.dataSource = [];
      const { current, pageSize } = this.pagination;
      let _query = `?pageNo=${current}&pageSize=${pageSize}`;
      _query += this.queryPathCache;

      $http.GetBeginningDataentryList(_query).then((res) => {
        // 分页
        let pagination = { ...this.pagination };

        pagination.total = res.result.total;
        pagination.pageSize = res.result.size;
        pagination.current = res.result.current;
        this.pagination = pagination; //分页
        this.maxSize = res.result.total;
        console.log("期初数据列表", res);
        const records = res.result.records;
        let renderTableData = [];

        const inventoryList = this.inventoryList;
        console.log("inventoryList::::", inventoryList);

        for (let i = 0; i < records.length; i++) {
          let data = {
            key: records[i].id, // 唯一值
            id: records[i].id,
            num: i + 1, // 序号
            balance: records[i].balance, //结存数量
            balanceAmount: records[i].balanceAmount, //结存金额
            createTime: records[i].createTime, //创建时间
            inventoryInformationId: records[i].inventoryInformationId, //存货id
            inventoryInformationId_dictText:
              records[i].inventoryInformationId_dictText, //存货名称
            inventoryOrganizationFileId: records[i].inventoryOrganizationFileId, //仓库id
            inventoryOrganizationFileId_dictText:
              records[i].inventoryOrganizationFileId_dictText, //仓库名称
            invspec: records[i].invspec,
            unit: records[i].unit,
            invcode: records[i].invcode,
            sort: records[i].sort, //分类value
            sort_dictText: records[i].sort_dictText, //分类
            startTime: records[i].startTime, //账期开始日期

            age: (function () {
              if (records[i].startTime) {
                let data1 = moment().format("YYYY-MM-DD"); //当前日期
                let data2 = records[i].startTime; //账期开始日期
                let data3 = moment(data1).diff(data2, "days"); //账龄
                console.log(data3);
                return data3;
              } else {
                return "";
              }
            })(),
          };
          // 进行数据筛选
          const inventory = inventoryList.filter(
            (item) =>
              item.inventoryInformationId === records[i].inventoryInformationId
          )[0];
          // 筛选到对应的数据 则进行赋值操作
          if (inventory) {
            Object.assign(data, {
              inventoryInformationId: inventory.inventoryInformationId, // 存货 id
              inventoryName: inventory.inventoryName, //存货名称
              invcode: inventory.invcode, //存货编码
              invspec: inventory.invspec, //存货规格型号
              unit: inventory.unit, //存货单位
            });
          }

          renderTableData.push(data);
        }
        this.dataSource = renderTableData;
        this.dataSourceCache = renderTableData;
        console.log("dataSource", this.dataSource);
      });
    },

    // 获取仓库
    getApplyStorage() {
      this.WarehouseCodeList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        //   // let tree = this.resetTree(res.result);
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            id: res.result[i].pkStordoc,
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            pkStordoc: res.result[i].pkStordoc,
          };
          this.WarehouseCodeList.push(data);
        }
        console.log("返回仓库编码、仓库名称", this.WarehouseCodeList);
      });
    },
    // 获取存货编码、名称、规格、单位
    getInventoryInformationByStorageId(id) {
      comHttp.getInventoryInformationByStorageId("?id=" + id).then((res) => {
        console.log("获取存货编码、名称、规格、单位", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            inventoryInformationId: res.result[i].id, // 存货 id
            inventoryName: res.result[i].inventoryName, //
            invcode: res.result[i].invcode,
            invspec: res.result[i].invspec,
            unit: res.result[i].unit,
          };
          this.inventoryList.push(data);
        }
        console.log("返回存货编码、存货名称", this.inventoryList);
      });
    },
    getInventoryClassificationList() {
      //获取存货分类
      this.treeDetilData = [];
      comHttp.GetSaveCargoClassification().then((res) => {
        console.log("存货分类！！！！！！！", res);
        this.inventoryNoList = res.result;
        this.disableParent(this.inventoryNoList);
      });
    },
    //禁用父节点
    disableParent(Tree) {
      const setData = Tree.map((item) => {
        if (item.children && item.children.length) {
          item[`disabled`] = true;
          this.disableParent(item.children);
        }
        return item;
      });
      return setData;
    },

    // 搜索栏选择存货编码编码的change触发函数
    inventoryNameChange(value, option) {
      this.searchForm.id = option.key;
      // console.log(value , option);
      const newValue = value.split("|");
      console.log("搜索栏选择了存货编码", newValue);
      this.searchForm.invcode = newValue[0];
      this.searchForm.inventoryName = newValue[1];
      this.searchForm.inventoryInformationId = newValue[2];
      this.searchForm.inventoryInformationId = newValue[4];
    },
    // 新增表单选择存货编码编码的change触发函数
    addinventoryNameChange(value, option) {
      let addForm = this.addForm;
      console.log("this.addForm2", this.addForm);
      addForm.id = option.key;

      const newValue = value.split("|");
      console.log("新增选择了存货编码", newValue);
      addForm.invcode = newValue[0];
      addForm.inventoryName = newValue[1];
      addForm.inventoryInformationId = newValue[2];
      addForm.invspec = newValue[2];
      addForm.inventoryInformationId = newValue[4];

      const inventoryList = this.inventoryList;
      let arr = inventoryList.filter(
        (item) => item.invcode === addForm.invcode
      );
      console.log(arr);
      addForm.inventoryName = arr[0].inventoryName;
      addForm.invspec = arr[0].invspec;
      addForm.unit = arr[0].unit;
      this.addForm = addForm;
      console.log("this.addForm", this.addForm);
    },
    //修改表单选择存货编码编码的change触发函数
    updateinventoryNameChange(value, option) {
      let updateForm = {};
      updateForm.id = option.key;

      // console.log(value , option);
      const newValue = value.split("|");
      console.log("新增选择了存货编码", newValue);
      updateForm.invcode = newValue[0];

      const inventoryList = this.inventoryList;
      let arr = inventoryList.filter(
        (item) => item.invcode === updateForm.invcode
      );
      console.log(arr);
      updateForm.inventoryName = arr[0].inventoryName;
      updateForm.invspec = arr[0].invspec;
      updateForm.unit = arr[0].unit;
      this.updateForm = updateForm;
    },
    // 分页函数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;

      this.GetBeginningDataentryList();
    },
    //存货分类-搜索
    sortchangeSearch(value, option) {
      console.log("选择的存货分类是:", `selected ${value}`);
      this.addForm.sort = value;
      console.log(option, "11");
    },
    //存货分类-新增、修改
    sortchange(value, option) {
      this.inventoryList = [];
      console.log("选择的存货分类是:", `selected ${value}`);
      console.log(option, "111111");
      //根据分类获取分类下的存货
      $http.getInventoryTypeGoodsInfo("?sort=" + value).then((res) => {
        console.log(res, "1213123123213");
        if (res.success) {
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              inventoryInformationId: res.result.list[i].id, // 存货 id
              inventoryName: res.result.list[i].inventoryName, //
              invcode: res.result.list[i].invcode, //
              invspec: res.result.list[i].invspec,
              unit: res.result.list[i].unit,
            };
            this.inventoryList.push(data);
          }

          // this.$message.success("成功获取" + option + "存货信息");
        }
      });
    },
    //过滤搜索
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    selectWarehouse(value) {
      //搜索表单的仓库名称的change
      let array = value.split("|");
      this.searchForm.depotName = array[1];
    },
    addWarehouse(value) {
      //添加表单的仓库名称的change
      console.log("value", value);
      let array = value.split("|");
      this.addForm.depotName = array[1];
      this.addForm.inventoryOrganizationFileId = array[2];
    },
    updateWarehouse(value) {
      //修改表单的仓库名称的change
      let array = value.split("|");
      this.updateForm.depotName = array[1];
      this.updateForm.inventoryOrganizationFileId = array[2];
    },
    addstorageUnitId(value) {
      //添加表单的所属单位的change
      let array = value.split("|");
      this.addForm.storageUnit = array[1];
      this.addForm.storageUnitId = array[2];
    },
    updatestorageUnitId(value) {
      //修改表单的所属单位的change
      let array = value.split("|");
      this.updateForm.storageUnit = array[1];
    },
    //选择仓库的chage
    /* ChangeWarehouse(value) {
      this.searchForm.depotName = `${value}`;
      this.ChooseWarehouse = `${value}`;
      console.log(this.ChooseWarehouse, "ChooseWarehouse");
    }, */
    // --- 修改按钮 ---
    editRecord(record) {
      console.log("修改：：：：", record);
      this.visible1 = !this.visible1;
      // this.updateForm = deepClone(record);
      // this.record = record;
      // id;
      this.updateForm.id = record.id; //id
      this.updateForm.balanceAmount = record.balanceAmount; //结存金额
      this.updateForm.balance = record.balance; //结存数量
      this.updateForm.createTime = record.createTime; //创建时间
      this.updateForm.startTime = record.startTime; //账龄起始日期
      this.updateForm.inventoryInformationId = record.inventoryInformationId; //存货id
      this.updateForm.inventoryInformationId_dictText =
        record.inventoryInformationId_dictText; //存货名称
      this.updateForm.inventoryName = record.inventoryName; //存货名称
      this.updateForm.invcode = record.invcode; //存货编码
      this.updateForm.inventoryOrganizationFileId_dictText =
        record.inventoryOrganizationFileId_dictText; //仓库名称
      this.updateForm.storageUnitId_dictText = record.storageUnitId_dictText; //所属单位
      this.updateForm.sort = record.sort; //分类value
      this.updateForm.sort_dictText = record.sort_dictText; //分别类
      this.updateForm.invspec = record.invspec; //规格型号
      this.updateForm.unit = record.unit; //规格型号
    },
    // -------修改弹窗取消------
    handleCancel1() {
      this.visible1 = false;
    },
    // --- 起初数据修改弹窗 确定修改 ---
    updateData() {
      // 获取数据

      const data = {
        id: this.updateForm.id,
        balance: Number(this.updateForm.balance),
        createTime: this.updateForm.createTime,
        startTime: this.updateForm.startTime,
        balanceAmount: this.updateForm.balanceAmount,
        // inventoryInformationId: 0,
        // inventoryOrganizationFileId: 0,
        // storageUnitId: 0,
      };
      // 发送请求
      $http.updateBeginningDataentry(data).then((res) => {
        console.log("修改");
        if (res.success) {
          this.$message.success("修改成功！");
          this.GetBeginningDataentryList();
          this.visible1 = false;
        } else {
          this.$message.success("修改失败！");
        }
      });
    },
    // 选择仓库编码的change触发函数
    DepotNameChange(value, option) {
      this.searchForm.id = option.key;
      // console.log(value , option);
      const newValue = value.split("|");
      console.log(newValue);
      this.searchForm.inventoryOrganizationFileId = newValue[2];
      this.searchForm.inventoryOrganizationFileId_dictText = newValue[1];
    },
    handleReset() {
      //重置
      this.searchForm = {
        //查询的表单
        inventoryOrganizationFileId: "", //仓库名称
        storageUnit: "", ///存储单位
        sort: "", //存货分类
        invcode: "", //存货编码
        inventoryName: "", //存货名称
      };

      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        // showSizeChanger: true,
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      this.queryPathCache = "";
      this.GetBeginningDataentryList();
    },
    /*  onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource.find((item) => item.key === key);
      if (target) {
        target[dataIndex] = value;
        this.dataSource = dataSource;
      }
    }, */
    onDelete(_id) {
      console.log("删除这一条", _id);
      const deletePath = `?id=${_id}`;
      $http
        .deleteBeginningDataentry(deletePath)
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("删除成功");
            this.GetBeginningDataentryList();
          } else {
            this.$message.error("删除失败");
          }
        })
        .then(() => {
          this.data = [];
        });
    },
    //新增弹窗
    addModal() {
      this.addVisible = true;
    },
    addCancel() {
      //新增弹窗-取消按钮
      this.addVisible = !this.addVisible;
      this.addForm = {
        //清空表单
        depotName: "", //仓库名称
        storageUnit: "", //所属单位
        sort: "", //存货分类
        invcode: "", //存货编码
        inventoryName: "", //存货名称
        invspec: "", //规格型号
        unit: "", //单位
        balance: "", //结存数量
        balanceAmount: "", //结存金额
        createtime: "", //创建时间
        starttime: "", //账龄起始日期
      };
    },
    addOk() {
      //新增弹窗的提交

      const data = {
        balance: Number(this.addForm.balance), //结存数量
        balanceAmount: Number(this.addForm.balanceAmount), //结存金额
        createTime: moment(this.addForm.createTime).format("YYYY-MM-DD"), //创建时间
        startTime: moment(this.addForm.startTime).format("YYYY-MM-DD"), //账龄起始日期
        inventoryOrganizationFileId: this.addForm.inventoryOrganizationFileId, //仓库
        storageUnitId: this.addForm.storageUnitId, //所属单位
        inventoryInformationId: this.addForm.inventoryInformationId, //存货编码（外键）
        sort: this.addForm.sort, //存货分类
      };
      console.log(data);

      /* let a = true;
      if (a) return; */
      $http.addBeginningDataentry(data).then((res) => {
        console.log("我进来了");
        if (res.success) {
          this.$message.success("保存成功！");
          this.addVisible = false; //关闭弹窗
          this.addForm = {
            //清空表单
            depotName: "", //仓库名称
            storageUnit: "", //所属单位
            sort: "", //存货分类
            invcode: "", //存货编码
            inventoryName: "", //存货名称
            invspec: "", //规格型号
            unit: "", //单位
            balance: "", //结存数量
            balanceAmount: "", //结存金额
            createtime: "", //创建时间
            starttime: "", //账龄起始日期
          };
          console.log(res);
          this.GetBeginningDataentryList();
        } else {
          this.$message.success("保存失败！");
        }
      });
    },

    // 导出
    // exportToExcel() {
    //   this.showSpin = true; //打印加载中
    //   if (this.searchForm.sort === undefined) {
    //     this.searchForm.sort = "";
    //   }
    //   if (this.searchForm.inventoryName === undefined) {
    //     this.searchForm.inventoryName = "";
    //   }
    //   $http
    //       .GetBeginningDataentryList("?pageNo=1&pageSize=" + this.maxSize)
    //       .then((res) => {
    //         console.log("导入的数据", res.result.records);
    //         let array = res.result.records;
    //         this.exportBasic(array);
    //       });
    // },
    exportToExcel() {
         this.queryPath =
          "?inventoryOrganizationFileId=" +
          this.searchForm.inventoryOrganizationFileId +
          "&sort=" +
          this.searchForm.sort +
          "&inventoryInformationId=" +
          this.searchForm.inventoryInformationId ;
        comHttp.beginningdataentryExportExcel(this.queryPath).then((response) => {
          //如果后端返回的result是进过Blob处理的，直接 window.URL.createObjectURL(result)，如果没有，就需要先实例化new Blod处理之后再window.URL.createObjectURL(blob)。
          //文件名 文件保存对话框中的默认显示
          let fileName = "期初数据.xls";
          let data = response.data;
          if (!data) {
            return;
          }
          console.log(response);
          //构造a标签 通过a标签来下载
          let url = window.URL.createObjectURL(new Blob([data]));
          let a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          //此处的download是a标签的内容，固定写法，不是后台api接口
          a.setAttribute("download", fileName);
          document.body.appendChild(a);
          //点击下载
          a.click();
          // 下载完成移除元素
          document.body.removeChild(a);
          // 释放掉blob对象
          window.URL.revokeObjectURL(url);
        });
    },



    // 接收数组，进行导出
    exportBasic(Array) {
      console.log("要导出的数据为:::::", Array);
      // 规整要导出的数据:::::
      let array = [];
      for (let i = 0; i < Array.length; i++) {
        let data = {
          序号: i + 1,
          仓库名称: Array[i].inventoryOrganizationFileId_dictText,
          存货分类: Array[i].sort_dictText,
          存货编码: Array[i].invcode,
          存货名称: Array[i].inventoryInformationId_dictText,
          规格型号: Array[i].invspec,
          单位: Array[i].unit,
          结存数量: Array[i].balance,
          结存金额: Array[i].balanceAmount,
          创建时间: Array[i].createTime,
          账龄起始日期: Array[i].startTime,
          账龄: Array[i].age,
        };
        array.push(data);
      }
      // 生成 sheet 表格 数据
      let sheet = XLSX.utils.json_to_sheet(array, {
        // 对导出内容进行相应的排序,手动排序。
        header: [
          "序号",
          "仓库名称",
          "存货分类",
          "存货编码",
          "存货名称",
          "规格型号",
          "单位",
          "结存数量",
          "结存金额",
          "创建时间",
          "账龄起始日期",
          "账龄（天）",
        ],
      });
      // 生成导出表格
      let blob = sheet2blob(sheet);
      try {
        FileSaver.saveAs(
          new Blob([blob], {
            type: "application/octet-stream",
          }),
          "期初信息.xlsx" // 导出文件夹名称
        );
      } catch (e) {
        console.log(e);
      }
      this.showSpin = false; //导出中
    },
  },
};
</script>

<style scoped>
.spin-content {
  border: 1px solid #91d5ff;
  background-color: #e6f7ff;
  padding: 30px;
}
</style>